from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify
import mysql.connector
from functools import wraps
import os
from dotenv import load_dotenv
from datetime import datetime
import hashlib
import uuid
import re

# 加载环境变量
load_dotenv()

app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'dev')

# 数据库配置
db_config = {
    'host': os.getenv('DB_HOST', 'localhost'),
    'user': os.getenv('DB_USER', 'root'),
    'password': os.getenv('DB_PASSWORD', '123456'),
    'database': os.getenv('DB_NAME', 'volunteer_db')
}

# 数据库连接函数
def get_db():
    return mysql.connector.connect(**db_config)

# 登录验证装饰器
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            flash('Please login first')
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

# 管理员验证装饰器
def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session or session.get('user_type') != 'admin':
            flash('Admin privileges required')
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

# 慈善机构验证装饰器
def charity_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session or session.get('user_type') != 'charity':
            flash('Charity organization privileges required')
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

# 密码加密函数
def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

# 首页路由
@app.route('/')
def index():
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    # 获取已审核的活动
    cursor.execute('''
        SELECT a.*, u.name as charity_name 
        FROM activities a 
        JOIN users u ON a.charity_id = u.id 
        WHERE a.status = 'approved' 
        ORDER BY a.created_at DESC 
        LIMIT 6
    ''')
    activities = cursor.fetchall()
    
    # 获取活跃的慈善机构
    cursor.execute('''
        SELECT u.*, COUNT(a.id) as activity_count 
        FROM users u 
        LEFT JOIN activities a ON u.id = a.charity_id 
        WHERE u.user_type = 'charity' AND u.status = 'active' 
        GROUP BY u.id 
        ORDER BY activity_count DESC 
        LIMIT 6
    ''')
    charities = cursor.fetchall()
    
    cursor.close()
    db.close()
    
    return render_template('index.html', activities=activities, charities=charities)

# 登录路由
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        email = request.form['email']
        password = hash_password(request.form['password'])
        
        db = get_db()
        cursor = db.cursor(dictionary=True)
        cursor.execute('SELECT * FROM users WHERE email = %s AND user_type != "admin"', (email,))
        user = cursor.fetchone()
        
        if user and password == user['password']:
            if user['status'] != 'active':
                flash('Your account is not activated or has been suspended')
                return redirect(url_for('login'))
                
            session['user_id'] = user['id']
            session['user_type'] = user['user_type']
            session['user_name'] = user['name']
            session['user_email'] = user['email']
            
            if user['user_type'] == 'volunteer':
                return redirect(url_for('volunteer_dashboard'))
            else:
                return redirect(url_for('charity_dashboard'))
                
        flash('Invalid email or password')
        cursor.close()
        db.close()
        
    return render_template('login.html')

# 注册路由
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        password = hash_password(request.form['password'])
        user_type = request.form['user_type']
        
        db = get_db()
        cursor = db.cursor()
        
        try:
            cursor.execute('SELECT * FROM users WHERE email = %s', (email,))
            if cursor.fetchone():
                flash('This email is already registered')
                return redirect(url_for('register'))
                
            cursor.execute('''
                INSERT INTO users (name, email, password, user_type, status)
                VALUES (%s, %s, %s, %s, %s)
            ''', (name, email, password, user_type, 'active'))
            
            db.commit()
            flash('Registration successful, please login')
            return redirect(url_for('login'))
            
        except mysql.connector.Error as err:
            flash(f'Registration failed: {err}')
        finally:
            cursor.close()
            db.close()
            
    return render_template('register.html')

# 退出登录
@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index'))

# 管理员仪表盘
@app.route('/admin/dashboard')
@admin_required
def admin_dashboard():
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    # 获取统计数据
    cursor.execute('SELECT COUNT(*) as count FROM users WHERE user_type = "volunteer"')
    volunteer_count = cursor.fetchone()['count']
    
    cursor.execute('SELECT COUNT(*) as count FROM users WHERE user_type = "charity"')
    charity_count = cursor.fetchone()['count']
    
    cursor.execute('SELECT COUNT(*) as count FROM activities')
    activity_count = cursor.fetchone()['count']
    
    cursor.execute('SELECT COUNT(*) as count FROM activities WHERE status = "pending"')
    pending_count = cursor.fetchone()['count']
    
    cursor.close()
    db.close()
    
    stats = {
        'volunteer_count': volunteer_count,
        'charity_count': charity_count,
        'activity_count': activity_count,
        'pending_activities': pending_count
    }
    
    return render_template('admin/dashboard_content.html', 
                         active_page='dashboard',
                         stats=stats)

# 管理员用户管理页面
@app.route('/admin/users')
@admin_required
def admin_users():
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    # 获取所有用户
    cursor.execute('SELECT * FROM users ORDER BY created_at DESC')
    users = cursor.fetchall()
    
    cursor.close()
    db.close()
    
    return render_template('admin/users_content.html',
                         active_page='users',
                         users=users)

# 管理员活动审核页面
@app.route('/admin/activities')
@admin_required
def admin_activities():
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    # 获取待审核活动
    cursor.execute('''
        SELECT a.*, u.name as charity_name 
        FROM activities a 
        JOIN users u ON a.charity_id = u.id 
        WHERE a.status = 'pending' 
        ORDER BY a.created_at DESC
    ''')
    pending_activities = cursor.fetchall()
    
    cursor.close()
    db.close()
    
    return render_template('admin/activities_content.html',
                         active_page='activities',
                         pending_activities=pending_activities)

# 志愿者仪表盘
@app.route('/volunteer/dashboard')
@login_required
def volunteer_dashboard():
    if session.get('user_type') != 'volunteer':
        flash('Access denied')
        return redirect(url_for('index'))
        
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    # 获取统计数据
    cursor.execute('''
        SELECT COUNT(*) as count 
        FROM registrations r 
        JOIN activities a ON r.activity_id = a.id 
        WHERE r.volunteer_id = %s AND a.status = 'completed'
    ''', (session['user_id'],))
    completed_count = cursor.fetchone()['count']
    
    cursor.execute('''
        SELECT COUNT(*) as count 
        FROM registrations r 
        JOIN activities a ON r.activity_id = a.id 
        WHERE r.volunteer_id = %s AND a.status = 'approved' AND a.start_time > NOW()
    ''', (session['user_id'],))
    upcoming_count = cursor.fetchone()['count']
    
    # 获取即将参与的活动
    cursor.execute('''
        SELECT a.*, u.name as charity_name 
        FROM activities a 
        JOIN users u ON a.charity_id = u.id 
        JOIN registrations r ON a.id = r.activity_id 
        WHERE r.volunteer_id = %s AND a.status = 'approved' AND a.start_time > NOW()
        ORDER BY a.start_time ASC
    ''', (session['user_id'],))
    upcoming_activities = cursor.fetchall()
    
    # 获取历史活动
    cursor.execute('''
        SELECT a.*, u.name as charity_name 
        FROM activities a 
        JOIN users u ON a.charity_id = u.id 
        JOIN registrations r ON a.id = r.activity_id 
        WHERE r.volunteer_id = %s AND a.status = 'completed'
        ORDER BY a.end_time DESC
    ''', (session['user_id'],))
    completed_activities = cursor.fetchall()
    
    stats = {
        'completed_activities': completed_count,
        'upcoming_activities': upcoming_count,
        'total_hours': 0  # 需要计算总服务时长
    }
    
    cursor.close()
    db.close()
    
    return render_template('volunteer/dashboard_content.html',
                         active_page='dashboard',
                         stats=stats,
                         upcoming_activities=upcoming_activities,
                         completed_activities=completed_activities)

# 志愿者个人资料
@app.route('/volunteer/profile')
@login_required
def volunteer_profile():
    if session.get('user_type') != 'volunteer':
        flash('Access denied')
        return redirect(url_for('index'))
        
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    cursor.execute('SELECT * FROM users WHERE id = %s', (session['user_id'],))
    profile = cursor.fetchone()
    
    cursor.close()
    db.close()
    
    return render_template('volunteer/profile_content.html',
                         active_page='profile',
                         profile=profile)

# 志愿者活动广场
@app.route('/volunteer/activities')
@login_required
def volunteer_activities():
    if session.get('user_type') != 'volunteer':
        flash('Access denied')
        return redirect(url_for('index'))
        
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    # 获取所有可报名的活动
    cursor.execute('''
        SELECT a.*, u.name as charity_name,
               (SELECT COUNT(*) FROM registrations r WHERE r.activity_id = a.id AND r.status = 'approved') as registered_count,
               (SELECT COUNT(*) FROM registrations r WHERE r.activity_id = a.id AND r.volunteer_id = %s) as is_registered
        FROM activities a 
        JOIN users u ON a.charity_id = u.id 
        WHERE a.status = 'approved' AND a.start_time > NOW()
        ORDER BY a.start_time ASC
    ''', (session['user_id'],))
    activities = cursor.fetchall()
    
    # 获取所有活动地点（用于筛选）
    cursor.execute('SELECT DISTINCT location FROM activities WHERE status = "approved"')
    locations = [row['location'] for row in cursor.fetchall()]
    
    cursor.close()
    db.close()
    
    # 添加当前时间用于计算活动状态
    now = datetime.now()
    
    return render_template('volunteer/activities_content.html',
                         active_page='activities',
                         activities=activities,
                         locations=locations,
                         now=now)

# 慈善机构仪表盘
@app.route('/charity/dashboard')
@charity_required
def charity_dashboard():
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    # 获取统计数据
    cursor.execute('''
        SELECT COUNT(*) as total_activities 
        FROM activities 
        WHERE charity_id = %s
    ''', (session['user_id'],))
    total_activities = cursor.fetchone()['total_activities']
    
    cursor.execute('''
        SELECT COUNT(DISTINCT u.id) as active_volunteers
        FROM users u
        JOIN registrations r ON u.id = r.volunteer_id
        JOIN activities a ON r.activity_id = a.id
        WHERE a.charity_id = %s AND r.status = 'approved' AND u.user_type = 'volunteer'
    ''', (session['user_id'],))
    active_volunteers = cursor.fetchone()['active_volunteers']
    
    cursor.execute('''
        SELECT COUNT(*) as pending_activities
        FROM activities
        WHERE charity_id = %s AND status = 'pending'
    ''', (session['user_id'],))
    pending_activities = cursor.fetchone()['pending_activities']
    
    stats = {
        'total_activities': total_activities,
        'active_volunteers': active_volunteers,
        'pending_activities': pending_activities
    }
    
    cursor.close()
    db.close()
    
    return render_template('charity/dashboard_content.html', stats=stats, active_page='dashboard')

# 机构信息页面
@app.route('/charity/profile')
@charity_required
def charity_profile():
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    cursor.execute('SELECT * FROM users WHERE id = %s', (session['user_id'],))
    profile = cursor.fetchone()
    
    cursor.close()
    db.close()
    
    return render_template('charity/profile_content.html', profile=profile, active_page='profile')

# 机构活动管理页面
@app.route('/charity/activities')
@charity_required
def charity_activities():
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    cursor.execute('''
        SELECT a.*, 
               COUNT(r.id) as registered_count
        FROM activities a
        LEFT JOIN registrations r ON a.id = r.activity_id
        WHERE a.charity_id = %s
        GROUP BY a.id
        ORDER BY a.created_at DESC
    ''', (session['user_id'],))
    activities = cursor.fetchall()
    
    cursor.close()
    db.close()
    
    return render_template('charity/activities_content.html', activities=activities, active_page='activities')

# 志愿者申请管理页面
@app.route('/charity/applications')
@charity_required
def charity_applications():
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    cursor.execute('''
        SELECT r.*, 
               u.name as volunteer_name,
               a.title as activity_title
        FROM registrations r
        JOIN users u ON r.volunteer_id = u.id
        JOIN activities a ON r.activity_id = a.id
        WHERE a.charity_id = %s AND r.status = 'pending' AND u.user_type = 'volunteer'
        ORDER BY r.created_at DESC
    ''', (session['user_id'],))
    applications = cursor.fetchall()
    
    cursor.close()
    db.close()
    
    return render_template('charity/applications_content.html', applications=applications, active_page='applications')

# 活动详情页
@app.route('/activities/<int:activity_id>')
def activity_detail(activity_id):
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    # 获取活动信息
    cursor.execute('''
        SELECT a.*, u.name as charity_name, u.description as charity_description,
               u.contact, u.phone, u.address,
               (SELECT COUNT(*) FROM registrations r WHERE r.activity_id = a.id AND r.status = 'approved') as registered_count
        FROM activities a 
        JOIN users u ON a.charity_id = u.id 
        WHERE a.id = %s
    ''', (activity_id,))
    activity = cursor.fetchone()
    
    if not activity:
        flash('Activity does not exist')
        return redirect(url_for('index'))
    
    # 检查当前用户是否已报名
    is_registered = False
    if 'user_id' in session:
        cursor.execute('''
            SELECT * FROM registrations 
            WHERE activity_id = %s AND volunteer_id = %s
        ''', (activity_id, session['user_id']))
        is_registered = cursor.fetchone() is not None
    
    # 获取已报名的志愿者
    cursor.execute('''
        SELECT u.name, r.created_at as registration_time 
        FROM registrations r 
        JOIN users u ON r.volunteer_id = u.id 
        WHERE r.activity_id = %s AND r.status = 'approved'
        ORDER BY r.created_at ASC
    ''', (activity_id,))
    registered_volunteers = cursor.fetchall()
    
    cursor.close()
    db.close()
    
    return render_template('activity_detail.html',
                         activity=activity,
                         charity=activity,
                         is_registered=is_registered,
                         registered_volunteers=registered_volunteers)

# 创建活动
@app.route('/activities/create', methods=['GET', 'POST'])
@charity_required
def create_activity():
    if request.method == 'POST':
        title = request.form['title']
        description = request.form['description']
        start_time = datetime.strptime(request.form['start_time'], '%Y-%m-%dT%H:%M')
        end_time = datetime.strptime(request.form['end_time'], '%Y-%m-%dT%H:%M')
        location = request.form['location']
        max_participants = int(request.form['max_participants'])
        required_skills = request.form.get('required_skills', '')
        notes = request.form.get('notes', '')
        
        db = get_db()
        cursor = db.cursor()
        
        try:
            cursor.execute('''
                INSERT INTO activities (
                    title, description, start_time, end_time, location,
                    max_participants, required_skills, notes, charity_id, status
                ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            ''', (
                title, description, start_time, end_time, location,
                max_participants, required_skills, notes, session['user_id'], 'pending'
            ))
            
            db.commit()
            flash('Activity created successfully, waiting for admin approval')
            return redirect(url_for('charity_dashboard'))
            
        except mysql.connector.Error as err:
            flash(f'Creation failed: {err}')
        finally:
            cursor.close()
            db.close()
            
    return render_template('activity_form.html')

# 编辑活动
@app.route('/activities/<int:activity_id>/edit', methods=['GET', 'POST'])
@charity_required
def edit_activity(activity_id):
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    # 获取活动信息
    cursor.execute('SELECT * FROM activities WHERE id = %s AND charity_id = %s',
                  (activity_id, session['user_id']))
    activity = cursor.fetchone()
    
    if not activity:
        flash('Activity does not exist or unauthorized to edit')
        return redirect(url_for('charity_dashboard'))
    
    if request.method == 'POST':
        title = request.form['title']
        description = request.form['description']
        start_time = datetime.strptime(request.form['start_time'], '%Y-%m-%dT%H:%M')
        end_time = datetime.strptime(request.form['end_time'], '%Y-%m-%dT%H:%M')
        location = request.form['location']
        max_participants = int(request.form['max_participants'])
        required_skills = request.form.get('required_skills', '')
        notes = request.form.get('notes', '')
        
        try:
            cursor.execute('''
                UPDATE activities 
                SET title = %s, description = %s, start_time = %s, end_time = %s,
                    location = %s, max_participants = %s, required_skills = %s,
                    notes = %s, status = 'pending'
                WHERE id = %s AND charity_id = %s
            ''', (
                title, description, start_time, end_time, location,
                max_participants, required_skills, notes, activity_id, session['user_id']
            ))
            
            db.commit()
            flash('Activity updated successfully, waiting for admin approval')
            return redirect(url_for('charity_dashboard'))
            
        except mysql.connector.Error as err:
            flash(f'Update failed: {err}')
        finally:
            cursor.close()
            db.close()
            
    return render_template('activity_form.html', activity=activity)

# API路由：更新用户状态
@app.route('/api/users/<int:user_id>/status', methods=['POST'])
@admin_required
def update_user_status(user_id):
    status = request.json.get('status')
    if status not in ['active', 'suspended']:
        return jsonify({'success': False, 'message': 'Invalid status'})
    
    db = get_db()
    cursor = db.cursor()
    
    try:
        cursor.execute('UPDATE users SET status = %s WHERE id = %s',
                      (status, user_id))
        db.commit()
        return jsonify({'success': True})
    except mysql.connector.Error as err:
        return jsonify({'success': False, 'message': str(err)})
    finally:
        cursor.close()
        db.close()

# API路由：更新活动状态
@app.route('/api/activities/<int:activity_id>/status', methods=['POST'])
@admin_required
def update_activity_status(activity_id):
    status = request.json.get('status')
    if status not in ['approved', 'rejected', 'completed']:
        return jsonify({'success': False, 'message': 'Invalid status'})
    
    db = get_db()
    cursor = db.cursor()
    
    try:
        cursor.execute('UPDATE activities SET status = %s WHERE id = %s',
                      (status, activity_id))
        db.commit()
        return jsonify({'success': True})
    except mysql.connector.Error as err:
        return jsonify({'success': False, 'message': str(err)})
    finally:
        cursor.close()
        db.close()

# API路由：报名活动
@app.route('/api/activities/<int:activity_id>/register', methods=['POST'])
@login_required
def register_activity(activity_id):
    if session.get('user_type') != 'volunteer':
        return jsonify({'success': False, 'message': 'Only volunteers can register for activities'})
    
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    try:
        # 检查活动是否存在且可报名
        cursor.execute('''
            SELECT * FROM activities 
            WHERE id = %s AND status = 'approved' 
            AND start_time > NOW()
        ''', (activity_id,))
        activity = cursor.fetchone()
        
        if not activity:
            return jsonify({'success': False, 'message': 'Activity does not exist or is not available for registration'})
        
        # 检查是否已报名
        cursor.execute('''
            SELECT * FROM registrations 
            WHERE activity_id = %s AND volunteer_id = %s
        ''', (activity_id, session['user_id']))
        if cursor.fetchone():
            return jsonify({'success': False, 'message': 'You have already registered for this activity'})
        
        # 检查名额
        cursor.execute('''
            SELECT COUNT(*) as count FROM registrations 
            WHERE activity_id = %s AND status = 'approved'
        ''', (activity_id,))
        current_count = cursor.fetchone()['count']
        
        if current_count >= activity['max_participants']:
            return jsonify({'success': False, 'message': 'Activity is full'})
        
        # 创建报名记录
        cursor.execute('''
            INSERT INTO registrations (activity_id, volunteer_id, status)
            VALUES (%s, %s, 'pending')
        ''', (activity_id, session['user_id']))
        
        db.commit()
        return jsonify({'success': True})
        
    except mysql.connector.Error as err:
        return jsonify({'success': False, 'message': str(err)})
    finally:
        cursor.close()
        db.close()

# API路由：取消报名
@app.route('/api/activities/<int:activity_id>/register', methods=['DELETE'])
@login_required
def cancel_registration(activity_id):
    if session.get('user_type') != 'volunteer':
        return jsonify({'success': False, 'message': 'Only volunteers can cancel registration'})
    
    db = get_db()
    cursor = db.cursor()
    
    try:
        cursor.execute('''
            DELETE FROM registrations 
            WHERE activity_id = %s AND volunteer_id = %s
        ''', (activity_id, session['user_id']))
        
        db.commit()
        return jsonify({'success': True})
        
    except mysql.connector.Error as err:
        return jsonify({'success': False, 'message': str(err)})
    finally:
        cursor.close()
        db.close()

# API路由：更新报名状态
@app.route('/api/applications/<int:application_id>/status', methods=['POST'])
@charity_required
def update_application_status(application_id):
    status = request.json.get('status')
    if status not in ['approved', 'rejected']:
        return jsonify({'success': False, 'message': 'Invalid status'})
    
    db = get_db()
    cursor = db.cursor(dictionary=True)
    
    try:
        # 检查申请是否存在且属于当前机构
        cursor.execute('''
            SELECT r.* FROM registrations r 
            JOIN activities a ON r.activity_id = a.id 
            WHERE r.id = %s AND a.charity_id = %s
        ''', (application_id, session['user_id']))
        
        if not cursor.fetchone():
            return jsonify({'success': False, 'message': 'Application does not exist or unauthorized to process'})
        
        cursor.execute('''
            UPDATE registrations 
            SET status = %s 
            WHERE id = %s
        ''', (status, application_id))
        
        db.commit()
        return jsonify({'success': True})
        
    except mysql.connector.Error as err:
        return jsonify({'success': False, 'message': str(err)})
    finally:
        cursor.close()
        db.close()

# 管理员登录路由
@app.route('/admin/login', methods=['GET', 'POST'])
def admin_login():
    if request.method == 'POST':
        email = request.form['email']
        password = hash_password(request.form['password'])
        
        db = get_db()
        cursor = db.cursor(dictionary=True)
        cursor.execute('SELECT * FROM users WHERE email = %s AND user_type = "admin"', (email,))
        user = cursor.fetchone()
        
        if user and password == user['password']:
            if user['status'] != 'active':
                flash('Account has been suspended')
                return redirect(url_for('admin_login'))
                
            session['user_id'] = user['id']
            session['user_type'] = user['user_type']
            session['user_name'] = user['name']
            session['user_email'] = user['email']
            return redirect(url_for('admin_dashboard'))
                
        flash('Invalid email or password')
        cursor.close()
        db.close()
        
    return render_template('admin/login.html')

# 更新志愿者资料
@app.route('/volunteer/profile/update', methods=['POST'])
@login_required
def update_volunteer_profile():
    if session.get('user_type') != 'volunteer':
        flash('Access denied')
        return redirect(url_for('index'))
        
    name = request.form['name']
    phone = request.form.get('phone', '')
    skills = request.form.get('skills', '')
    
    db = get_db()
    cursor = db.cursor()
    
    try:
        cursor.execute('''
            UPDATE users 
            SET name = %s, phone = %s, description = %s
            WHERE id = %s AND user_type = 'volunteer'
        ''', (name, phone, skills, session['user_id']))
        
        db.commit()
        
        # 只更新session中的用户名
        session['user_name'] = name
        
        flash('Profile updated successfully')
    except mysql.connector.Error as err:
        flash(f'Update failed: {err}')
    finally:
        cursor.close()
        db.close()
    
    return redirect(url_for('volunteer_profile'))

# 更新慈善机构资料
@app.route('/charity/profile/update', methods=['POST'])
@charity_required
def update_charity_profile():
    name = request.form['name']
    description = request.form.get('description', '')
    contact = request.form.get('contact', '')
    phone = request.form.get('phone', '')
    address = request.form.get('address', '')
    
    db = get_db()
    cursor = db.cursor()
    
    try:
        cursor.execute('''
            UPDATE users 
            SET name = %s, description = %s, contact = %s, phone = %s, address = %s
            WHERE id = %s AND user_type = 'charity'
        ''', (name, description, contact, phone, address, session['user_id']))
        
        db.commit()
        
        # 只更新session中的用户名
        session['user_name'] = name
        
        flash('Profile updated successfully')
    except mysql.connector.Error as err:
        flash(f'Update failed: {err}')
    finally:
        cursor.close()
        db.close()
    
    return redirect(url_for('charity_profile'))

if __name__ == '__main__':
    app.run(debug=True)